import time

import torch
import torchvision.datasets
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm

train_data = torchvision.datasets.CIFAR10("../dataset", train=True, download=True,
                                          transform=torchvision.transforms.ToTensor())
train_dataloader = DataLoader(train_data, batch_size=1, shuffle=True, num_workers=0, drop_last=False)

test_data = torchvision.datasets.CIFAR10("../dataset", train=False, download=False,
                                         transform=torchvision.transforms.ToTensor())
test_dataloader = DataLoader(test_data, batch_size=1, shuffle=True, num_workers=0, drop_last=False)


class MyMod(nn.Module):
    def __init__(self):
        super(MyMod, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(in_features=1024, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

    def forward(self, x):
        output = self.model(x)
        return output


device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print("start on {} device.".format(device))
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练数据集长度: {}".format(train_data_size))
print("测试数据集长度: {}".format(test_data_size))
# 创建网络模型
mymod = MyMod()
mymod = mymod.to(device)
# 损失函数
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)

# 优化器
# learning_rate = 0.01
# 1e-2=1 x (10)^(-2) = 1 /100 = 0.01
learning_rate = 1e-2
optimizer = torch.optim.SGD(mymod.parameters(), lr=learning_rate)

# 训练的轮数
epoch = 1

for i in range(epoch):
    mymod.train()
    start_time = time.time()
    losses = []
    accuracy = []
    for data in train_dataloader:
        imgs, targets = data
        imgs = imgs.to(device)
        targets = targets.to(device)
        outputs = mymod(imgs)

        loss = loss_fn(outputs, targets)
        losses.append(loss)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    end_time = time.time()
    tqdm.write("第{}轮训练用时：{} s".format(i, end_time - start_time))

    mymod.eval()
    test_total_loss = 0
    test_total_accuracy = 0
    # 去掉梯度
    with torch.no_grad():
        for data in test_dataloader:
            imgs, targets = data
            imgs = imgs.to(device)
            targets = targets.to(device)
            outputs = mymod(imgs)

            loss = loss_fn(outputs, targets)
            test_total_loss += loss.item()
            # 统计在测试集上正确的个数，然后累加起来
            accuracy = (outputs.argmax(1) == targets).sum()
            test_total_accuracy += accuracy

    print("测试集上的总体loss：{}".format(test_total_loss))
    # 精度=测试集上正确的总数/测试集的数量
    print("测试集上的总体accuracy：{}".format(test_total_accuracy / test_data_size))

torch.save(mymod, "./mymod.pth")

# 绘图

